package com.authine.cloudpivot.ext.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptUtils {

    public enum Mode {
        /**
         *
         */
        MD5_32(0, "MD5"),
        MD5_40(1, "MD5"),
        SHA(2, "SHA"),
        SHA_1(2, "SHA-1"),
        SHA_512(3, "SHA-512");

        public Integer id;
        public String text;

        private Mode(Integer id, String text) {

            this.id = id;
            this.text = text;
        }

        public static Mode get(Integer code) {

            for (Mode c : Mode.values()) {
                if (c.id.toString().equals(code.toString())) return c;
            }

            return null;
        }

        @Override
        public String toString() {
            return text;
        }
    }

    private static String encrypt(Mode mode, String value) {

        if (value == null) return "";

        MessageDigest digest;

        try {
            digest = MessageDigest.getInstance(mode.text);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(mode.text + " algorithm not available.");
        }

        try {
            byte[] bytes = digest.digest(value.getBytes(StringUtils.UTF8));
            String length = "40";
            if (mode == Mode.MD5_32) {
                length = "32";
            }
            return String.format("%0" + length + "x", new BigInteger(1, bytes));
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(StringUtils.UTF8 + " encoding not available.");
        }
    }

    public static String MD5_40(String value) {

        return encrypt(Mode.MD5_40, value);

    }

    public static String MD5_32(String value) {

        return encrypt(Mode.MD5_32, value);

    }

    public static String SHA(String value) {

        return encrypt(Mode.SHA, value);
    }

    public static String SHA_1(String value) {

        return encrypt(Mode.SHA_1, value);
    }

    public static String SHA_512(String value) {

        return encrypt(Mode.SHA_512, value);
    }
}

